package com.dengqi.mymodule.activity.loader.bitmap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.loader.content.AsyncTaskLoader;

/**
 * Created by dell on 2019/5/10
 */
public class BitmapLoader extends AsyncTaskLoader<Bitmap> {

    private String urlPath = "";
    private BitmapCollection.BitmapCallbacks callbacks;

    public BitmapLoader(@NonNull Context context) {
        super(context);
    }

    public void setUrlPath(String urlPath) {
        this.urlPath = urlPath;
    }

    public void setCallBack(BitmapCollection.BitmapCallbacks callbacks) {
        this.callbacks = callbacks;
    }

    @Nullable
    @Override
    public Bitmap loadInBackground() {
        //    通过Apache的HttpClient来访问请求网络中的一张图片
        HttpURLConnection connection;
        Bitmap bitmap = null;
        try {
            URL url = new URL(urlPath);
            connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false);
            InputStream inputStream = connection.getInputStream();
            //方法一
//                bitmap = BitmapFactory.decodeStream(inputStream);
            //方法二
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 得到文件的总长度
            int file_length = connection.getContentLength();
            // 每次读取后累加的长度
            int total_length = 0;
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) != -1) {
                // 每读一次，就将total_length累加起来
                total_length += length;
                // 边读边写到ByteArrayOutputStream当中
                byteArrayOutputStream.write(buffer, 0, length);
                // 得到当前图片下载的进度
                int progress = (int) ((total_length / (float) file_length) * 100);
                // 时刻将当前进度更新给onProgressUpdate方法
                //                publishProgress(progress);
                if (callbacks!=null) {
                    callbacks.onProgressUpdate(progress);
                }

            }
            bitmap = BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, file_length);
            inputStream.close();
            byteArrayOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
